# coding: utf-8
# 端口开通申请接口
import json
import time
from collections import defaultdict

import requests
from requests.adapters import HTTPAdapter


class S_Client(object):
    def __init__(self):
        self.timeout = 20
        self.hu_data_url = "http://web.juhe.cn/finance/stock/shall"
        self.key = "2dabc2315c6189545ca2b86af7422d16"
        self.s = requests.Session()
        self.s.mount("http://", HTTPAdapter(max_retries=5))
        self.s.mount("https://", HTTPAdapter(max_retries=5))
        self.headers = {
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        }
        self.headers["User-Agent"] = (
            "Mozilla/5.0 (Windows NT 6.3; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36"
        )
        self.headers["Content-Type"] = "application/x-www-form-urlencoded"

    def get_hu_data(self):
        page_type = 4
        single_page_data_size = 80

        data_list = []
        url = "{}?stock=&page=&type={}&key={}".format(
            self.hu_data_url, page_type, self.key
        )
        res = self.s.get(
            url,
            headers=self.headers,
            verify=False,
            timeout=self.timeout,
            allow_redirects=False,
        )
        res_json = res.json()
        if int(res_json["error_code"]) == 0:
            print("数据获取成功")
            totalCount = int(res_json["result"]["totalCount"])
            page_nunber = totalCount // single_page_data_size + 1
            for p in range(1, page_nunber + 1):
                time.sleep(2)
                data_url = "{}?stock=&page={}&type={}&key={}".format(
                    self.hu_data_url, p, page_type, self.key
                )
                print(data_url)
                res = self.s.get(
                    data_url,
                    headers=self.headers,
                    verify=False,
                    timeout=self.timeout,
                    allow_redirects=False,
                )
                res_json = res.json()
                if int(res_json["error_code"]) == 0:
                    # print(res_json["result"]["data"])
                    data_list.extend(res_json["result"]["data"])
                else:
                    print("数据获取失败")
        else:
            print("数据获取失败")
        return data_list


def get_hu_infos():
    client = S_Client()
    hu_data_list = client.get_hu_data()
    with open("hu_data.txt", "w") as f:
        data = json.dumps(hu_data_list)
        f.write(data)


get_hu_infos()
